import { useEffect, useRef, useState } from "react";
import Grid from "../grid";
import { date } from "../helpers";
import useStore from "../store";
import Task from "../task-list";
import styles from "./style.module.less";
import { TaskProps } from "../types";

interface GanttProps {
  height: number;
}

const Gantt = (props: GanttProps) => {
  const tasks = useStore((state) => state.tasks);
  const expendCount = useStore((state) => state.expendCount);
  const scrollTop = useStore((state) => state.scrollTop);
  const setScrollTop = useStore((state) => state.setScrollTop);
  const setScrollLeft = useStore((state) => state.setScrollLeft);
  const [startDate, endDate] = date.getTasksRange(tasks);
  const days = date.getDatesInRange(startDate, endDate);
  const showTaskRef = useRef(0);
  const [showTasks, setShowTasks] = useState(0);
  const scrollYRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const showTasks = (ts: TaskProps[]) => {
      ts.map((t) => {
        if (t.children && t.children.length > 0 && t.toggle) {
          showTasks(t.children);
        }
        showTaskRef.current = showTaskRef.current + 1;
        setShowTasks(showTaskRef.current);
      });
    };
    showTaskRef.current = 0;
    setShowTasks(0);
    showTasks(tasks);
  }, [expendCount]);
  useEffect(() => {
    if (scrollYRef.current) {
      scrollYRef.current.scrollTop = scrollTop;
    }
  }, [scrollTop]);
  return (
    <div
      className={styles.container}
      style={{ height: `${props.height - 2}px` }}
    >
      <div
        style={{
          position: "absolute",
          bottom: "0px",
          left: "400px",
          width: "calc(100% - 400px - 16px)",
          overflowX: "scroll",
          zIndex: 1,
        }}
        onScroll={(e) => {
          setScrollLeft(e.currentTarget.scrollLeft);
        }}
      >
        <div style={{ width: `${days.length * 40}px`, height: "1px" }}></div>
      </div>
      <div
        style={{
          position: "absolute",
          right: "0px",
          top: "60px",
          height: "calc(100% - 60px - 16px - 2px)",
          overflowY: "scroll",
          zIndex: 1,
        }}
        ref={scrollYRef}
        onScroll={(e) => {
          setScrollTop(e.currentTarget.scrollTop);
        }}
      >
        <div style={{ width: "1px", height: `${showTasks * 40}px` }}></div>
      </div>
      <div className={styles.task}>
        <Task height={props.height - 16} />
      </div>
      <div className={styles.grid}>
        <Grid height={props.height - 16} />
      </div>
    </div>
  );
};

export default Gantt;
